package com.crm.dataReceive.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.crm.custinfo.domain.CustCommentRecord;
import com.crm.custinfo.domain.CustInfo;
import com.crm.custinfo.domain.HitPackage;
import com.crm.custinfo.service.ICustCommentRecordService;
import com.crm.custinfo.service.ICustInfoService;
import com.crm.custinfo.service.IHitPackageService;
import com.crm.dataReceive.domain.BaseApi;
import com.crm.dataReceive.domain.Customer;
import com.crm.dataReceive.domain.RpQxhReq;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.AesUtils;
import com.ruoyi.common.utils.Md5Encrypt;
import com.ruoyi.common.utils.ObjectUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Validated
@RestController
@RequestMapping("/qxh")
public class RpQxhController extends BaseController {
    @Autowired
    private IHitPackageService hitPackageService;
    @Autowired
    private ICustInfoService custInfoService;
    @Autowired
    private ICustCommentRecordService custCommentRecordService;

    private static final String miyao = "MCXBIjANke";//本媒体编号 channel_source
    @Anonymous
    @PostMapping("check/tenant/{tenantId}")
    @ResponseBody
    public Map<String, Object> check(@RequestBody RpQxhReq req) {
        String[] defaultarr = new String[]{};
        Map<String, Object> defaultData = new HashMap<>();

        try {
            String getdate = AesUtils.decryptHex(req.getSigns(), getkey(req));
            if (StringUtils.isBlank(getdate)) {
                return Result("-1", "解密失败", defaultData);
            }
            JSONObject jsonObject = JSONObject.parseObject(getdate);
            String mobileMask = jsonObject.getString("mobileMask");
            if (StringUtils.isBlank(mobileMask) || mobileMask.length() != 11) {
                return Result("-1", "九位号码异常", defaultData);
            }
            // 追加先验证  channel 编号
            String channel_source = jsonObject.getString("system");
            if (StringUtils.isBlank(channel_source)) {
                return Result("-1", "系统来源异常", defaultData);
            }
            //log.info("{}撞库明文：{}", channel_source, mobileMask);

            String city = jsonObject.getString("city").replace("市", "");


            HitPackage hitPackage = new HitPackage();
            hitPackage.setMobilePrefix9md5(Md5Encrypt.md5(mobileMask.substring(0, 9)));
            List<HitPackage> custs= hitPackageService.selectHitPackageList(hitPackage);
            if (CollectionUtils.isNotEmpty(custs)) {
                defaultarr = new String[custs.size()];
                for (int i = 0; i < custs.size(); i++) {
                    defaultarr[i] = custs.get(i).getMobileMd5();
                }
            }

            String dataStr = JSON.toJSONString(defaultarr);
            Map<String, Object> listdata = new HashMap<>();
            listdata.put("md5List", dataStr);

            String sig = AesUtils.encryptHex(JSON.toJSONString(listdata), getkey(req));

            defaultData.put("timestamp", req.getTimestamp());
            defaultData.put("signs", sig);

        } catch (Exception e) {
            logger.error("qxh撞库异常：" + e.getMessage());
            return Result("-9", "api处理异常", defaultData);
        }

        return Result("200", "success", defaultData);
    }
    @Anonymous
    @PostMapping("apply/tenant/{tenantId}")
    @ResponseBody
    public Map<String, Object> apply(@RequestBody RpQxhReq req) {
        Map<String, Object> defaultData = new HashMap<>();

        try {
            String getdate = AesUtils.decryptHex(req.getSigns(), getkey(req));
            if (StringUtils.isBlank(getdate)) {
                return Result("-1", "解密失败", defaultData);
            }
            JSONObject jsonObject = JSONObject.parseObject(getdate);

            String mobile = jsonObject.getString("mobile");
            if (StringUtils.isBlank(mobile) || mobile.length() != 11) {
                return Result("-1", "获取号码异常", defaultData);
            }

            String userName = jsonObject.getString("userName");
            String city = jsonObject.getString("city");
            int applyLimit = jsonObject.getIntValue("applyLimit");
            String sex = jsonObject.getString("sex");
            Long age = jsonObject.getLong("age");
            String channel_source = jsonObject.getString("system");

            if (StringUtils.isBlank(userName) || StringUtils.isBlank(city) || StringUtils.isBlank(sex) || StringUtils.isBlank(channel_source)) {
                return Result("-1", "参数获取异常", defaultData);
            }

            Customer customer = new Customer();
            customer.setMobile(mobile);
            customer.setCustName(userName);
            customer.setCity(city);
            String limit = applyLimit * 10000 + "";
            customer.setApplyLimit(new BigDecimal(StringUtils.defaultIfBlank(limit, "0")));
            customer.setSex(StringUtils.defaultIfBlank(sex, "0"));
            customer.setAge(age);// 年龄
            customer.setChannelSource(channel_source);
            CustInfo custInfo = new CustInfo();
            ObjectUtil.copyProperties(customer, custInfo);
            custInfo.setRepeatFlag("0");
            String md5value = Md5Encrypt.md5(customer.getMobile());
            if (custInfo.getApplyTime() == null) {
                custInfo.setApplyTime(new Date());
            }
            custInfo.setMd5val(md5value);
            // 分发系统唯一id
            custInfo.setDistributeId(-1L);
            logger.info("线索接收API请求转换：{}", custInfo.toString());
            // 客户申请信息前置检查
            Map<String, Object> checkResult = custInfoService.checkCustInfo(custInfo, logger);
            if (MapUtils.getIntValue(checkResult, "errorNo", -1) != 0) {
                return Result("-1", MapUtils.getString(checkResult, "errorInfo", ""), defaultData);
            }
            // 随机分配
            Long[] orgIds = custInfoService.getOrgIdsByCity(custInfo.getCity());
            boolean isSucceed = custInfoService.dealCustRandomly(custInfo, orgIds, true, false, logger);
            if (isSucceed) {
                if (StringUtils.isNotBlank(custInfo.getRemark())) {
                    // 自动生成一条备注
                    CustCommentRecord record = new CustCommentRecord();
                    record.setCustId(custInfo.getId());
                    record.setEmpId(null);
                    record.setEmpName("系统自动备注");
                    record.setRemark(custInfo.getRemark());
                    record.setType(1L);
                    record.setType2(1L);
                    record.setCreateTime(new Date());
                    custCommentRecordService.insertCustCommentRecord(record);
                }
            } else {

                return Result("-1", "线索接收API请求申请异常", defaultData);
            }
            return Result("200", "成功", defaultData);

        } catch (Exception e) {
            logger.error("qxh异常：" + e.getMessage());
            return Result("-9", "api处理异常", defaultData);
        }
    }

    private String getkey(RpQxhReq req) {
        return String.format("%s%s", miyao, req.getTimestamp()).substring(0, 16);
    }

    private Map<String, Object> Result(String result, String msg, Map<String, Object> data) {
        Map<String, Object> resMap = new HashMap<>(4);
        resMap.put("result", result);
        resMap.put(BaseApi.MESSAGE, msg);
        resMap.put(BaseApi.DATA, data);
        return resMap;
    }

    public static void main(String[] args) {
//        Map<String, Object> sigmap = new HashMap<>();
//        sigmap.put("mobileMask", "137000000**");
//        sigmap.put("city", "北京");
//        sigmap.put("system", "qxh");
//        String sigmapstr = JSON.toJSONString(sigmap);
//        String times = "1717724899024";
//        String key = String.format("%s%s", "MCXBIjANke", times).substring(0, 16);
//        String sig = "";
//        try {
//            sig = AesUtils.encryptHex(sigmapstr, key);
//
//        } catch (Exception e) {
//            logger.error("qxh撞库异常：" + e.getMessage());
//        }
//        System.out.println(sig);
////jiemi  signs -> Ud8qXWf5KElIYxSPx6qqJ1a5j4YJaFtf2R6TgaJaMOfjfSAz+8KY2FAAc2bCMlGWmQPeToOV7pliKTCJK1F1OQ==
//
//        try {
//            System.out.println(AesUtils.decryptHex("Ud8qXWf5KElIYxSPx6qqJ1a5j4YJaFtf2R6TgaJaMOfjfSAz+8KY2FAAc2bCMlGWmQPeToOV7pliKTCJK1F1OQ==", key));
//        } catch (Exception e) {
//            logger.error("qxh撞库异常：" + e.getMessage());
//        }
//
//        try {
//            String nk = "MCXBIjANke172749";
//            // String sig =  SecureUtil.des(getkey(req).getBytes(StandardCharsets.UTF_8)).encryptHex(JSON.toJSONString(listdata));
//
//            //System.out.println(AesUtils.decryptHex("091ad004163e8b3f251c67bb4932621a6129072decfe63285f44204870f14ab5e67e68cfc9556d477e281feddf022c38c31ac21cffd7a925d63e74e8263ab38404ccd637cb920aa9077ef5c6e30adf7a89238ff0c82f466dd0799f35da15870a6be2d8b5eb857caba5b298367bc304be23bbb496ce1706eaca7318f75d509974350a4ad161b8c4457b7bf94b2f96f6c83d3723fb26c8e518b74b40f2e7d574e9c0acf71052513b946e2e7d99013fa1d3c33521dd56d63b0056777ffe0ec12c31e17c763ae714877d0812594501a27a9fd947bd1e39249b4e533629c6df4582049fbbce5cd82388659e80aeab5ad8f3424fb9ecf959153ccea98749d30c45656159beb6d3192df8b31527fd97351f17b73a5c53d7a0e459c77e91e4799ce7de07040a4ba2b2b105972a6d30a4b3ee01b00383c502cb453cd767a6c5c34ba1c221", "MCXBIjANke172748"));
//            System.out.println("11111111");
//            System.out.println(AesUtils.decryptHex("ae5419affe1881884cbf65c9094eef4800c93cfee852e79b511f45ff70b3f99ffb45e7182ff2857238ef816cf777dbaa9376d371ea83735b6b3993b0475d800eda70dd74fda9884679cf33d917765012d17c514d41f17e66fd9978a0819da680", "MCXBIjANke172749"));
//
//
//        } catch (Exception e) {
//            log.error("qxh撞库异常：" + e.getMessage());
//        }


    }
}
